package com.xuecheng.content.service.Impl;

import com.xuecheng.content.mapper.CourseCategoryMapper;
import com.xuecheng.content.model.dto.CourseCategoryTreeDto;
import com.xuecheng.content.service.CourseCategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class CourseCategoryServiceImpl implements CourseCategoryService {

    @Autowired
    CourseCategoryMapper courseCategoryMapper;

    /**
     * 课程分类
     * @param id
     * @return
     */
    @Override
    public List<CourseCategoryTreeDto> selectTreeNodes(String id) {
        //1.先获取数据
        List<CourseCategoryTreeDto> courseCategoryTreeList= courseCategoryMapper.selectTreeNodes(id);

        //2.转成map方便封装数据返回
        // (key1, key2) -> key2是一个合并函数，用于处理在收集过程中可能出现的键冲突。在这里，如果有重复的键出现，保留后一个键对应的值
        Map<String, CourseCategoryTreeDto> categoryTreeDtoMap = courseCategoryTreeList.stream().filter(item -> !id.equals(item.getId())).collect(Collectors.toMap(key -> key.getId(), value -> value, (key1, key2) -> key2));
        
        //3.定义返回对象
        List<CourseCategoryTreeDto> resultCategoryTreeList = new ArrayList<>();


        //4. 处理对象
        courseCategoryTreeList.stream().filter(item->!id.equals(item.getId())).forEach(item ->{
            if (item.getParentid().equals(id)){
                //说明是1-1类型的
                resultCategoryTreeList.add(item);
            }

            //找到当前节点的父节点
            CourseCategoryTreeDto courseCategoryTreeDto = categoryTreeDtoMap.get(item.getParentid());
            if (courseCategoryTreeDto != null){
                if (courseCategoryTreeDto.getChildrenTreeNodes() == null){
                    //初始化
                    courseCategoryTreeDto.setChildrenTreeNodes(new ArrayList<CourseCategoryTreeDto>());
                }
                courseCategoryTreeDto.getChildrenTreeNodes().add(item);
            }
        });
        return resultCategoryTreeList;
    }
}
